const express = require('express')
const router = express.Router()
const { channel, novel } = require('novel-parser')
const { request } = require('../utils')
const { ADD_NOVEL, NOVEL_LIST, GET_NOVEL, DOWNLOAD_NOVEL, UPDATE_NOVEL } = channel
const urls = require('../constants/urls')
const { GET_NOVEL_CHAPTER, SEARCH_NOVEL, SEARCH_NOVEL_WITH_ID, EDIT_NOVEL } = require('novel-parser/lib/servies/channel')

router.get.apply(router, request(urls[NOVEL_LIST], async () => {
  return novel[NOVEL_LIST]()
}))

router.post.apply(router, request(urls[ADD_NOVEL], async (req) => {
  return novel[ADD_NOVEL](req.body)
}))

router.get.apply(router, request(urls[SEARCH_NOVEL], async (res) => {
  return novel[SEARCH_NOVEL_WITH_ID](res.query)
}))

router.post.apply(router, request(urls[DOWNLOAD_NOVEL], async (res) => {
  return novel[DOWNLOAD_NOVEL](res.body)
}))

router.post.apply(router, request(urls[UPDATE_NOVEL], async (res) => {
  return novel[UPDATE_NOVEL](res.body)
}))

router.get.apply(router, request(urls[GET_NOVEL_CHAPTER], async (res) => {
  const arg = res.query
  arg.refresh = arg.refresh === 'true'
  return novel[GET_NOVEL_CHAPTER](arg)
}))

router.get.apply(router, request(urls[GET_NOVEL], async (req) => {
  return novel[GET_NOVEL]({ _id: req.params.id })
}))

router.put.apply(router, request(urls[EDIT_NOVEL], async (req) => {
  return novel[EDIT_NOVEL](req.body)
}))

module.exports = router
